// 获取cookie
function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) === " ") {
      c = c.substring(1, c.length);
    }
    if (c.indexOf(nameEQ) === 0) {
      return c.substring(nameEQ.length, c.length);
    }
  }
  return null;
}

// 页数
function page() {
  const page = parseInt(document.getElementsByClassName("goNum")[0].value);
  const pageNumber = document.getElementsByClassName("pageNumber")[0];
  console.log(page);

  if (page < parseInt(getCookie("total")) + 1 && page > 0) {
    pageNumber.innerHTML = page;
  }
  userList();
}

//翻页
function goBack() {
  const pageNumber = document.getElementsByClassName("pageNumber")[0];
  if (pageNumber.textContent > 1) {
    pageNumber.textContent--;
    userList();
  }
}

function next() {
  const pageNumber = document.getElementsByClassName("pageNumber")[0];
  if (pageNumber.textContent < getCookie("total")) {
    pageNumber.textContent++;
    userList();
  }
}

// 查询
function Search() {
  const pageNumber = document.getElementsByClassName("pageNumber")[0];
  pageNumber.innerHTML = 1;
  userList();
}

// 列表渲染
function userList() {
  const page = parseInt(
    document.getElementsByClassName("pageNumber")[0].textContent
  );
  const size = parseInt(document.getElementsByClassName("size")[0].textContent);
  const token = localStorage.getItem("token");
  const Search = document.getElementsByClassName("inputSearch")[0].value;
  let data;
  if (Search === "") {
    data = {
      page: page,
      size: size,
    };
  } else {
    data = {
      Search: Search,
      page: page,
      size: size,
    };
  }

  axios
    .get("http://127.0.0.1:3000/api/v1/userInformation/userList", {
      params: data,
      headers: {
        authorization: token,
        "Content-Type": "application/json", // 如果发送的是JSON数据，设置这个头部
      },
    })
    .then(function (res) {
      if (res.status == 200) {
        if (res.data.code == 0) {
          // 存储cookie总页码数
          total = Math.ceil(res.data.data.total[0].total / size);
          document.cookie = "total=" + total;
          let allTotal = document.getElementsByClassName("allTotals")[0]
          allTotal.innerHTML = getCookie("total")
          // 渲染页面
          const formTdDivs = document.querySelectorAll("div.formTd");
          // 遍历并删除每个元素
          formTdDivs.forEach((formTdDiv) => {
            formTdDiv.parentNode.removeChild(formTdDiv);
          });
          for (var i = 0; i < size; i++) {
            let formTd = document.createElement("div");
            formTd.className = "formTd";
            formTd.innerHTML = `<div class="formTd">
            <div class="formTxt">
              ${res.data.data.list[i].id}
            </div>
            <div class="formTxt">
              ${res.data.data.list[i].loginname}
            </div>
            <div class="formTxt">
              ${res.data.data.list[i].username}
            </div>
            <div class="formTxt">
              ${res.data.data.list[i].img}
            </div>
            <div class="formTxt handle">
              <div class="update"  onclick="addListHidenupdate(${res.data.data.list[i].id},'${res.data.data.list[i].loginname}','${res.data.data.list[i].username}')">
                编辑
              </div>
              <div class="delete" data-index=${res.data.data.list[i].id} onclick="delList(event)">
                删除
              </div>
            </div>
          </div>`;
            const form = document.getElementsByClassName("form")[0];
            form.appendChild(formTd);
          }
        } else {
        }
      } else {
      }
    })
    .catch(function (error) {
      console.log(error);
    });
}
userList();

// 显示添加
function addListHiden() {
  const mask = document.getElementsByClassName("mask")[0];
  mask.style.display = "block";
}

// 显示修改
function addListHidenupdate(id,loginname,username) { 
  const mask = document.getElementsByClassName("maskupdate")[0];
  mask.setAttribute('data-id', id);
  mask.style.display = "block";
  const loginnameValue = document.getElementById("loginnameValue");
  loginnameValue.value = loginname
  const usernameValue = document.getElementById("usernameValue");
  usernameValue.value = username
  console.log(usernameValue.value);
  console.log(loginnameValue.value);
  
}

// 关闭添加
function closeWindows() {
  const mask = document.getElementsByClassName("mask")[0];
  mask.style.display = "none";
}

// 关闭修改
function closeWindowsupdate() {
  const mask = document.getElementsByClassName("maskupdate")[0];
  mask.style.display = "none";
}

// 添加
function addList() {
  const loginNameValue = document.getElementById("loginnameValue").value;
  const passWordValue = document.getElementById("passwordValue").value;
  const userNameVale = document.getElementById("usernameValue").value;
  if (loginNameValue && userNameVale && passWordValue) {
    axios
      .post("http://127.0.0.1:3000/api/v1/user/register", {
        loginname: loginNameValue,
        username: userNameVale,
        password: passWordValue,
      })
      .then(function (res) {
        if (res.status == 200) {
          if (res.data.code === 0) {
            const mask = document.getElementsByClassName("mask")[0];
            mask.style.display = "none";
            userList();
          } else {
            alert("注册失败");
          }
          console.log(res);
        } else {
          alert("注册失败");
        }
      })
      .catch(function (error) {
        console.log(error);
        alert("注册失败");
      });
  } else {
    alert("格式错误请注意格式");
  }
}



// 删除
function delList(e) {
  const token = localStorage.getItem("token");
  let index = parseInt(e.target.dataset.index)
    axios
      .get("http://127.0.0.1:3000/api/v1/userInformation/delete", {
        params:{
          id:index
        },
        headers: {
          authorization: token
        },
      })
      .then(function (res) {
        if (res.status == 200) {
          if (res.data.code === 0) {
            alert('删除成功')
            userList();
          } else {
            alert("删除失败");
          }
          console.log(res);
        } else {
          alert("删除失败");
        }
      })
      .catch(function (error) {
        console.log(error);
        alert("删除失败");
      });
  }


  // 修改
function updateList() {
  const token = localStorage.getItem("token");
  const indexId = document.getElementsByClassName('maskupdate')[0].dataset.id;
  const loginname = document.getElementById('loginnameValues').value
  const username = document.getElementById('usernameValues').value
  
    axios
      .get("http://127.0.0.1:3000/api/v1/userInformation/update", {
        params:{
          id:indexId,
          loginname: loginname,
          username: username
        },
        headers: {
          authorization: token
        },
      })
      .then(function (res) {
        if (res.status == 200) {
          if (res.data.code === 0) {
            alert('修改成功')
            closeWindowsupdate()
            userList();
          } else {
            alert("修改失败");
          }
          console.log(res);
        } else {
          alert("修改失败");
        }
      })
      .catch(function (error) {
        console.log(error);
        alert("修改失败");
      });
  }
